import {useLocation} from 'react-router-dom';
import { Toast } from 'antd-mobile';
import api from '../config/api';
import code from "./code";


let count = 0;
const http = {
  hiddenLoading() {
    count > 0 || Toast.hide();
  },
  showLoading() {
    count++;
    count === 1 && setTimeout(() => {Toast.loading('loading...', 0)});
  },
  stringify(data = {}) {
    let esc = encodeURIComponent;
    let query = Object.keys(data)
      .map((k) => esc(k) + '=' + esc(data[k]))
      .join('&');
    return query;
  },
  useQuery() {
    return new URLSearchParams(useLocation().search);
  },
  checkStatus(res) {
    if (res.ok) return res;
    count = 0;
    this.hiddenLoading();
    Toast.fail('请求错误');
    throw new Error('err');
  },
  async _request(url, config = {}) {
    try {
      this.showLoading();
      let res = await fetch(api.proxy + url, config);
      let result = await this.checkStatus(res).json();
      count--;
      this.hiddenLoading();
      if(result.result === -1){
        Toast.fail(result.message,1.5);
        // return new Promise(()=>{})

        return new Promise(resolve=>{
          resolve(result)
        })
      }
      else return result;

    } catch (error) {
      // console.dir(error);
      if (error.message !== 'err') {
        count = 0;
        this.hiddenLoading();
        window.alert('网络错误'+url+JSON.stringify(config));
        // throw error;
      }
    }
  },
  async get(url, data = {}) {
    let user = await code.getUser();
    data.hosId = user.hosId;
    data.userId =user.userid;
    data.managerId=user.managerId
    // data.hosId = '1';
    let query = this.stringify(data);
   
    return await this._request(url + '?' + query);
  },
  async post(url, data = {}) {
    let user = await code.getUser();
    // let check = await code.checkBind()
    // console.log("员工信息",user)
    data.hosId = user.hosId;
    data.userId = user.userid;
    // data.userId = 'SG03133'; // 暂时写死 
    data.managerId = user.managerId;
    let query = this.stringify(data);
    return await this._request(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },//放在url后面
      body: query,
    });
  },
  async post_json(url, data = {}) {
    let user = await code.getUser();
    // let check = await code.checkBind()
    //console.log("员工信息",user)
    data.hosId = user.hosId;
    data.userId = user.userid;
    data.managerId = user.managerId;
    // data.userId = 'SG03133'; // 暂时写死 
    return await this._request(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },//放在request body中
      body: JSON.stringify(data),
    });
  },


  // 综合模式
  async post_all(url, data = {}) {
    let user = await code.getUser();
    // let check = await code.checkBind()
    //console.log("员工信息",user)
    // data.hosId = user.hosId;
    // data.userId = user.userid;
    // data.managerId = user.managerId;
    let str = "?hosId="+ user.hosId +"&userId=" + user.userid +"&managerId=" + user.managerId
    // data.userId = 'SG03133'; // 暂时写死 
    return await this._request(url+str, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },//放在request body中
      body: JSON.stringify(data),
    });
  },

  







  async outPost(url, data = {}) {
    let query = this.stringify(data);
    return await this._request(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: query,
    });
  },
};

export default http;
